package com.newbee.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.Notification.Builder;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.hhu.newbee.R;
import com.newbee.activity.LoginActivity;
import com.newbee.activity.tab.MainActivity;
import com.newbee.activity.tab.NewMsgActivity;
import com.newbee.activity.tab.NewQunZu;
import com.newbee.app.OnRefrushActivity;
import com.newbee.app.SpeechApp;
import com.newbee.fragement.QunzuFragment;
import com.newbee.fragement.multchat.MultChatFragement;
import com.newbee.http.ServerHttpUtil;
import com.newbee.listbean.FriendsInfoBean;
import com.newbee.listbean.QunZuInfoBean;
import com.newbee.smack.SmackClient;
import com.newbee.sound.SoundRecorder;
import com.newbee.sqlite.DBHelper;

public class MainService extends Service implements Runnable
{

	private static Queue<MainServiceTask> taskQueue = new LinkedList<MainServiceTask>();
	private static Map<String, OnRefrushActivity> activityMap = new HashMap<String, OnRefrushActivity>();
	private static boolean _isRunable = false;

	private DBHelper dbHelper = new DBHelper(this);
	public static String SHARE_TO_SINA_SUCCESS = "SHARE_TO_SINA_SUCCESS";
	public static String SHARE_TO_SINA_FALSE = "SHARE_TO_SINA_FALSE";

	public static Map<String, OnRefrushActivity> speticalAcitivity = new HashMap<String, OnRefrushActivity>();

	private NotificationManager notificationManager;

	private static final int NOTIFY_ASK_FRIEND = 1;
	private static final int NOTIFY_QZ = 2;
	public static final int CMD_STOP_SERVICE = 0;
	private CommandReceiver cmdReceiver;

	public static final String STOP_SERVICE = "STOP_SERVICE";

	public static final String CMD = "CMD";

	public static void stopService()
	{
		_isRunable = false;
	}

	private Handler _handler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{

			// 获取参数列表的内容

			Map<String, Object> map = (Map<String, Object>) msg.obj;

			// 要刷新的activity
			OnRefrushActivity BA = (OnRefrushActivity) activityMap.get(map
					.get(MainServiceTask.ACTIVITY_NAME));

			switch (msg.what)
			{

			case TaskType.USER_LOGIN:
			{

				boolean tag = (Boolean) map
						.get(MainServiceKey.USER_LOG_RETURN_INFO);

				String nickName = (String) map.get(MainServiceKey.NICK_NAME);
				String head = (String) map.get(MainServiceKey.HEAD);
				String userName = (String) map.get(MainServiceKey.USERNAME);

				if (BA != null)
				{

					BA.refresh(TaskType.USER_LOGIN, tag, nickName, head,
							userName);
				}

				break;
			}
			case TaskType.CONFERENCE_GET_FRIEND:
			{
				List<FriendsInfoBean> list = (List<FriendsInfoBean>) map
						.get(MainServiceKey.GET_FRIEND_RESPONSE);
				BA.refresh(TaskType.CONFERENCE_GET_FRIEND, list);

				break;
			}
			case TaskType.GET_FRIEND:
			{

				List<FriendsInfoBean> list = (List<FriendsInfoBean>) map
						.get(MainServiceKey.GET_FRIEND_RESPONSE);
				if (BA != null)
				{
					BA.refresh(TaskType.GET_FRIEND, list);
				}
				break;
			}

			case TaskType.REFRUSH_FRIEND:
			{
				List<FriendsInfoBean> list = (List<FriendsInfoBean>) map
						.get(MainServiceKey.GET_FRIEND_RESPONSE);
				if (BA != null)
				{
					BA.refresh(TaskType.REFRUSH_FRIEND, list);
				}
				break;
			}
			case TaskType.ASK_FOR_FRIEND:
			case TaskType.INVITE_MULT_CHAT:
			{

				OnRefrushActivity ba = speticalAcitivity.get(MainActivity.class
						.getName());

				if (ba != null)
				{
					ba.refresh(TaskType.MAIN_MSG, null);
				}
				ba = speticalAcitivity.get(NewMsgActivity.class.getName());
				if (ba != null)
				{
					ba.refresh(TaskType.ASK_FOR_FRIEND, null);
				}
				break;
			}
			case TaskType.ASCEPT_FRIEND:
			{

				if (BA != null)
				{
					BA.refresh(TaskType.ASCEPT_FRIEND, map
							.get(MainServiceKey.ASK_FOR_FRIEND_POCKET_RESPONSE));
				}
				break;
			}

			case TaskType.CREATE_MULT_CHAT:
			{

				boolean jur = (Boolean) map
						.get(MainServiceKey.CREATE_MULT_CHAT_RESPONSE);

				List<String> userList = (List<String>) map
						.get(MainServiceKey.INVITE_FRIEND_LIST);
				String roomName = ((String) map
						.get(MainServiceKey.MULT_CHAT_ROOM_NAME)).split("@")[0];
				if (BA != null)
				{
					BA.refresh(TaskType.CREATE_MULT_CHAT, jur, roomName,
							userList);
				}

				// 更新群组列表

				OnRefrushActivity ref = speticalAcitivity.get(NewQunZu.class
						.getName());
				if (ref != null)
				{
					ref.refresh(TaskType.CREATE_MULT_CHAT, roomName, userList);
				}

				break;
			}
			case TaskType.MULT_CHAT_MSG:
			{
				String roomName = (String) map
						.get(MainServiceKey.MULT_CHAT_ROOM_NAME);
				String from = (String) map.get(MainServiceKey.MULT_CHAT_FROM);
				String body = (String) map.get(MainServiceKey.MULT_CHAT_BODY);
				boolean isFrom = (Boolean) map.get(MainServiceKey.MULT_IS_FROM);
				String date = (String) map.get(MainServiceKey.MULT_CHAT_DATE);
				OnRefrushActivity.RtInfo rt = null;
				if (BA != null)
				{
					rt = BA.refresh(TaskType.MULT_CHAT_MSG, roomName, from,
							body, isFrom, date);
				}

				if ((rt != null && rt.tag == false) || rt == null)
				{

					OnRefrushActivity ref = speticalAcitivity
							.get(QunzuFragment.class.getName());
					if (ref != null)
					{
						ref.refresh(TaskType.MULT_CHAT_MSG, roomName);
					}

				}
				break;
			}
			case TaskType.MULT_SEND_MSG:
			{
				// do nothing!
				break;
			}

			case TaskType.GET_QUNZU:
			{

				List<QunZuInfoBean> list = (List<QunZuInfoBean>) map
						.get(MainServiceKey.QUNZU_LIST);

				if (BA != null && list != null)
				{
					BA.refresh(TaskType.GET_QUNZU, list);
				}

				break;
			}

			case TaskType.TRANS:
			{

				String result = (String) map.get(MainServiceKey.RESULT_STRING);

				if (BA != null)
				{
					BA.refresh(TaskType.TRANS, result);
				}
				break;

			}
			case TaskType.ACCEPT_MULT:
			{

				boolean result = (Boolean) map
						.get(MainServiceKey.ACCEPT_MJLT_RESP);

				String roomName = (String) map
						.get(MainServiceKey.MULT_CHAT_ROOM_NAME);
				if (BA != null)
				{
					BA.refresh(TaskType.ACCEPT_MULT, result);

				}

				break;

			}
			case TaskType.SINGLE_VOICE_RECOG:
			{
				String result = (String) map.get(MainServiceKey.RESULT_STRING);
				if (BA != null)
				{
					BA.refresh(TaskType.SINGLE_VOICE_RECOG, result);

				}
				break;

			}
			case TaskType.USER_REGIST:
			{

				boolean re = (Boolean) map.get(MainServiceKey.RESULT_STRING);
				if (BA != null)
				{
					BA.refresh(TaskType.USER_REGIST, re);

				}

				break;
			}

			case TaskType.ADD_FRIEND_GET_NICKNAME:
			{
				String nickName = (String) map.get(MainServiceKey.NICK_NAME);
				String head = (String) map.get(MainServiceKey.HEAD);
				boolean re = (Boolean) map.get(MainServiceKey.ADD_FRIEND_RESP);
				String username = (String) map.get(MainServiceKey.USERNAME);
				if (BA != null)
				{
					BA.refresh(TaskType.ADD_FRIEND_GET_NICKNAME, re, nickName,
							head, username);

				}
				break;
			}
			case TaskType.INVATE_FRIEND:
			{
				boolean re = (Boolean) map.get(MainServiceKey.RESULT_STRING);

				if (BA != null)
				{
					BA.refresh(TaskType.INVATE_FRIEND, re);

				}

				break;
			}
			case TaskType.REG_EMAIL_VF:
			{

				String code = (String) map.get(MainServiceKey.VF_CODE);
				if (BA != null)
				{
					BA.refresh(TaskType.REG_EMAIL_VF, code);
				}

				break;
			}
			case TaskType.FORGET_PASSWORD:
			{

				boolean resp = (Boolean) map.get(MainServiceKey.RESULT_STRING);
				if (BA != null)
				{
					BA.refresh(TaskType.FORGET_PASSWORD, resp);
				}

				break;
			}
			case TaskType.BEFORE_SHARE_QQ:
			{

				String resp = (String) map.get(MainServiceKey.RESULT_STRING);
				if (BA != null)
				{
					BA.refresh(TaskType.BEFORE_SHARE_QQ, resp);
				}

				break;
			}

			case TaskType.CHECK_SPELL:
			{
				String resp = (String) map.get(MainServiceKey.RESULT_STRING);
				if (BA != null)
				{
					BA.refresh(TaskType.CHECK_SPELL, resp);
				}
				break;
			}
			default:
				break;
			}

		}

	};

	public static void removeActivity(String activityName)
	{

		if (activityMap.containsKey(activityName) == true)
		{
			activityMap.remove(activityName);
		}

	}

	private void initReceiver()
	{
		cmdReceiver = new CommandReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(STOP_SERVICE);
		registerReceiver(cmdReceiver, intentFilter);
	}

	public static void addSpecialActivity(String key, OnRefrushActivity UI)
	{

		if (speticalAcitivity.containsKey(key))
		{
			return;
		}
		else
		{
			speticalAcitivity.put(key, UI);
		}

	}

	@Override
	public void onCreate()
	{
		super.onCreate();

		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		_isRunable = true;
		initReceiver();
		new Thread(this).start();

	}

	@Override
	public IBinder onBind(Intent arg0)
	{
		return null;
	}

	/**
	 * 加入优先队列
	 * 
	 * @param T
	 */
	public static void addTaskQueue(MainServiceTask T)
	{
		taskQueue.add(T);
	}

	public static void addActivityMap(String activityname,
			OnRefrushActivity activity)
	{

		if (activityMap.containsKey(activityname) == true)
		{
			// do nothing!!
		}
		else
		{
			activityMap.put(activityname, activity);
		}
	}

	public static void setStop()
	{
		_isRunable = false;
	}

	public void run()
	{
		// TODO Auto-generated method stub
		Log.d("WCH", "login run--------->start");
		try
		{
			/**
			 * init xmpp设置
			 */

			SmackClient.getInstance().initConfig();

		}
		catch (Exception e)
		{
			Log.d("WCH", "init xmpp------->problem!" + e.toString());
			e.printStackTrace();
		}

		try
		{
			MainServiceTask task = null;
			while (this._isRunable)
			{

				if (taskQueue.isEmpty() == false)
				{

					task = taskQueue.poll();
					if (null != task)
					{
						doTask(task);
					}
				}
				Thread.sleep(300);
			}
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}

	private void doTask(final MainServiceTask T)
	{

		Message message = new Message();
		message.what = T.get_taskID();// 获取任务id

		/*
		 * 向handler传递的信息 包括类名字
		 */
		Map<String, Object> messageObjectMap = new HashMap<String, Object>();
		messageObjectMap.put(MainServiceTask.ACTIVITY_NAME,
				T.get_activityName());// 设置类的名字

		switch (T.get_taskID())
		{
		case TaskType.USER_LOGIN:// 用户登录
		{

			Map<String, Object> pars = T.get_task();
			String account = (String) pars.get(LoginActivity.ACCOUNT);
			String password = (String) pars.get(LoginActivity.PASSWORD);
			SmackClient sc = SmackClient.getInstance();

			String re = ServerHttpUtil.getNiceName(account.replace("@", "#"));

			Log.d("JSON", "json----->" + re);

			try
			{
				JSONObject jo = new JSONObject(re);

				String nickename = jo.getString("nickName");
				String head = jo.getString("head");

				String userName = jo.getString("username");
				String pureHead = head.split("\\.")[0];
				messageObjectMap.put(MainServiceKey.HEAD, pureHead);
				messageObjectMap.put(MainServiceKey.NICK_NAME, nickename);
				messageObjectMap.put(MainServiceKey.USERNAME, userName);

				if (nickename != null && head != null)
				{
					sc.userLog(account.replace("@", "#") + "$" + nickename
							+ "$" + pureHead, password);
					messageObjectMap.put(MainServiceKey.USER_LOG_RETURN_INFO,
							true);
				}
				else
				{
					messageObjectMap.put(MainServiceKey.USER_LOG_RETURN_INFO,
							false);
				}
			}
			catch (Exception e)
			{
				messageObjectMap
						.put(MainServiceKey.USER_LOG_RETURN_INFO, false);
				e.printStackTrace();
			}

			break;
		}
		case TaskType.CONFERENCE_GET_FRIEND:
		case TaskType.REFRUSH_FRIEND:
		case TaskType.GET_FRIEND:
		{

			List<FriendsInfoBean> list = SmackClient.getInstance()
					.getAllFriedns();
			// 这个地方要发送消息，获取所有的email的friends

			if (list.size() != 0)
			{
				String result = ServerHttpUtil.getUserName(list);
				try
				{
					if (result != null)
					{
						SpeechApp.setUserNamePair(new JSONObject(result));
					}
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			messageObjectMap.put(MainServiceKey.GET_FRIEND_RESPONSE, list);

			break;
		}
		case TaskType.ASK_FOR_FRIEND:
		{
			Map<String, Object> pars = T.get_task();

			String from = (String) pars
					.get(MainServiceKey.ASK_FOR_FRIEND_POCKET_FROM);
			String to = (String) pars
					.get(MainServiceKey.ASK_FOR_FRIEND_POCKET_TO);

			Log.d(MainService.class.getName(), "ask friend from----------->"
					+ from);
			Log.d(MainService.class.getName(), "ask friend to----------->" + to);
			Presence presence = null;
			presence = new Presence(Type.subscribed);
			presence.setTo(to);
			presence.setFrom(from);
			SmackClient.connection.sendPacket(presence);
			presence = new Presence(Type.subscribed);
			presence.setTo(from);
			presence.setFrom(to);
			SmackClient.connection.sendPacket(presence);
			List<String> list = SmackClient.getInstance().getAllFriendsID();
			if (list.contains(from))
			{
				message.what = TaskType.STOP;
			}
			else
			{
				dbHelper.insertNewFriendAskMsg(from, to);

				Notification.Builder builder = new Builder(this);
				builder.setSmallIcon(R.drawable.ic_launcher_mini);
				builder.setContentTitle("加好友通知");
				builder.setContentText("有添加好友请求！");
				builder.setTicker("有添加好友请求！");
				builder.setWhen(System.currentTimeMillis());
				Notification notification = builder.getNotification();
				notification.defaults = Notification.DEFAULT_SOUND;
				notificationManager.notify(NOTIFY_ASK_FRIEND, notification);
			}
			break;
		}

		case TaskType.ASCEPT_FRIEND:
		{
			Map<String, Object> pars = T.get_task();
			SmackClient sc = SmackClient.getInstance();
			try
			{
				sc.acceptAskFriend(
						pars.get(MainServiceKey.ASK_FOR_FRIEND_POCKET_FROM)
								.toString(),
						pars.get(MainServiceKey.ASK_FOR_FRIEND_POCKET_TO)
								.toString());
				messageObjectMap.put(
						MainServiceKey.ASK_FOR_FRIEND_POCKET_RESPONSE, true);
			}
			catch (Exception e)
			{
				messageObjectMap.put(
						MainServiceKey.ASK_FOR_FRIEND_POCKET_RESPONSE, false);
				e.printStackTrace();
			}

			break;
		}

		case TaskType.INVITE_MULT_CHAT:
		{
			Notification.Builder builder = new Builder(this);
			builder.setSmallIcon(R.drawable.ic_launcher_mini);
			builder.setContentTitle("协同录音通知");
			builder.setContentText("有协同录音请求！");
			builder.setTicker("有协同录音请求！");
			builder.setWhen(System.currentTimeMillis());
			Notification notification = builder.getNotification();
			notification.defaults = Notification.DEFAULT_SOUND;
			notificationManager.notify(NOTIFY_QZ, notification);

			Map<String, Object> pars = T.get_task();
			String roomname = (String) pars
					.get(MainServiceKey.MULT_CHAT_ROOM_NAME);
			dbHelper.insertNewMultChatInvite(roomname);
			break;
		}
		case TaskType.CREATE_MULT_CHAT:
		{
			Map<String, Object> paras = T.get_task();

			List<String> inviteUser = (List<String>) paras
					.get(MainServiceKey.INVITE_FRIEND_LIST);
			String conferenceName = (String) paras
					.get(MainServiceKey.MULT_CHAT_ROOM_NAME);

			messageObjectMap.put(MainServiceKey.MULT_CHAT_ROOM_NAME,
					conferenceName);
			messageObjectMap.put(MainServiceKey.INVITE_FRIEND_LIST, inviteUser);
			try
			{

				StringBuffer sb = new StringBuffer("");
				int length = inviteUser.size();

				for (int i = 0; i < length - 1; i++)
				{
					sb.append(inviteUser.get(i).split("@")[0]);
					sb.append(";");
				}
				sb.append(inviteUser.get(length - 1).split("@")[0]);

				ServerHttpUtil.postQunZuInfo(conferenceName,
						SmackClient.connection.getUser().split("@")[0],
						sb.toString());

				// 这个订房要将群组上传的服务器了

				messageObjectMap.put(MainServiceKey.CREATE_MULT_CHAT_RESPONSE,
						true);
			}
			catch (Exception e)
			{
				messageObjectMap.put(MainServiceKey.CREATE_MULT_CHAT_RESPONSE,
						false);
				e.printStackTrace();
			}

			break;
		}

		case TaskType.MULT_CHAT_MSG:
		{

			Map<String, Object> paras = T.get_task();
			String roomName = (String) paras
					.get(MainServiceKey.MULT_CHAT_ROOM_NAME);
			String from = (String) paras.get(MainServiceKey.MULT_CHAT_FROM);
			String body = (String) paras.get(MainServiceKey.MULT_CHAT_BODY);
			String date = new SimpleDateFormat("yyyy-MM-dd HH:mm")
					.format(new Date());

			boolean isfrom = false;
			String userAccount = SmackClient.connection.getUser();
			if (from.endsWith(userAccount))// 当当前用户的名称等于来的人的名称时候,这说明是要往外发生的啦
			{
				// 往外发送的消息啦
				// do nothing!
			}
			else
			{
				// 别人发送给你的的消息啦
				isfrom = true;
			}

			messageObjectMap.put(MainServiceKey.MULT_CHAT_DATE, date);
			messageObjectMap.put(MainServiceKey.MULT_CHAT_ROOM_NAME, roomName);
			messageObjectMap.put(MainServiceKey.MULT_CHAT_FROM, from);
			messageObjectMap.put(MainServiceKey.MULT_CHAT_BODY, body);
			messageObjectMap.put(MainServiceKey.MULT_IS_FROM, isfrom);
			break;

		}
		case TaskType.MULT_SEND_MSG:
		{

			Map<String, Object> paras = T.get_task();
			String msgType = (String) paras.get(MainServiceKey.MSG_TYPE);
			final String mRoomName = (String) paras
					.get(MainServiceKey.MULT_CHAT_ROOM_NAME);// pure
			// md5
			int durTime = (Integer) paras.get(MainServiceKey.MULT_DUR);
			final String voiceName = (String) paras
					.get(MainServiceKey.MULT_FILE_VOICE);

			SharedPreferences sp = getSharedPreferences(
					LoginActivity.SP_USER_INFO, Activity.MODE_MULTI_PROCESS);
			final String userName = sp.getString(LoginActivity.SP_KEY_USERNAME,
					"N/A");

			final int langType = (Integer) paras.get(MainServiceKey.LANG_TYPE);

			if (msgType.equals(MultChatFragement.TYPE_NORMAL))
			{
				new Thread()
				{

					@Override
					public void run()
					{
						ServerHttpUtil.userUpLoad(new File(SoundRecorder.DIR
								+ voiceName), mRoomName, userName, langType);
					}
				}.start();

			}
			try
			{
				SmackClient.getInstance().sendMultMsg(mRoomName, voiceName,
						durTime + "", msgType);
				messageObjectMap.put(MainServiceKey.SEND_MSG_RESPONSE, true);
			}
			catch (XMPPException e)
			{
				messageObjectMap.put(MainServiceKey.SEND_MSG_RESPONSE, false);

				e.printStackTrace();
			}

			break;
		}

		case TaskType.GET_QUNZU:
		{

			JSONArray ja;
			try
			{
				// SmackClient.connection.connect();
				ja = ServerHttpUtil.getQunZu(SmackClient.connection.getUser()
						.split("@")[0]);

			}
			catch (Exception e1)
			{
				e1.printStackTrace();

				SharedPreferences sp = getSharedPreferences(
						LoginActivity.REMBER_ACCOUNT,
						Activity.MODE_MULTI_PROCESS);

				String userAccount = sp.getString(
						LoginActivity.CURRENT_ACCOUNT, null);
				String userPassword = sp.getString(
						LoginActivity.CURRENT_PUSSWORD, null);

				if (userAccount != null && userPassword != null)
				{
					Map<String, Object> pars = new HashMap<String, Object>();
					pars.put(LoginActivity.ACCOUNT, userAccount);
					pars.put(LoginActivity.PASSWORD, userPassword);
					MainServiceTask mst = new MainServiceTask(
							TaskType.USER_LOGIN, pars,
							LoginActivity.class.getName());
					MainService.addTaskQueue(mst);
				}
				messageObjectMap.put(MainServiceKey.QUNZU_LIST, null);

				break;
			}

			int length = ja.length();
			List<QunZuInfoBean> list = new ArrayList<QunZuInfoBean>();

			List<String> userList = null;
			JSONObject jo;

			QunZuInfoBean bean;

			String qunzuName;

			JSONArray userArray;
			try
			{
				for (int i = 0; i < length; i++)
				{
					jo = ja.getJSONObject(i);

					qunzuName = jo.getString("qunzu");
					userArray = jo.getJSONArray("userlist");
					userList = new ArrayList<String>();
					for (int j = 0; j < userArray.length(); j++)
					{
						userList.add(userArray.getString(j));
					}
					list.add(new QunZuInfoBean(qunzuName, userList));
				}
			}
			catch (JSONException e)
			{
				e.printStackTrace();
			}
			messageObjectMap.put(MainServiceKey.QUNZU_LIST, list);
			break;

		}

		case TaskType.TRANS:
		{

			Map<String, Object> paras = T.get_task();
			String tag = (String) paras.get(MainServiceKey.TRANS_TAG);

			String resultString = ServerHttpUtil.multChatTrans(tag);

			messageObjectMap.put(MainServiceKey.RESULT_STRING, resultString);
			break;
		}

		case TaskType.ACCEPT_MULT:
		{

			Map<String, Object> paras = T.get_task();

			String roomName = (String) paras
					.get(MainServiceKey.MULT_CHAT_ROOM_NAME);

			try
			{
				SmackClient.getInstance().acceptInviteMultChat(roomName);

				messageObjectMap.put(MainServiceKey.MULT_CHAT_ROOM_NAME,
						roomName);
				messageObjectMap.put(MainServiceKey.ACCEPT_MJLT_RESP, true);
			}
			catch (XMPPException e)
			{
				messageObjectMap.put(MainServiceKey.ACCEPT_MJLT_RESP, false);
				e.printStackTrace();
			}

			break;
		}

		case TaskType.SINGLE_VOICE_RECOG:
		{

			Map<String, Object> paras = T.get_task();

			String fileName = (String) paras
					.get(MainServiceKey.SINGLE_FILE_NAME);

			int type = (Integer) paras.get(MainServiceKey.LANG_TYPE);

			String resp = ServerHttpUtil.simgleVoiceFile(fileName, type + "");

			messageObjectMap.put(MainServiceKey.RESULT_STRING, resp);

			break;
		}

		case TaskType.USER_REGIST:
		{

			Map<String, Object> paras = T.get_task();

			String email = (String) paras.get(MainServiceKey.EMAIL);
			String nickName = (String) paras.get(MainServiceKey.NICK_NAME);
			String password = (String) paras.get(MainServiceKey.PASSWORD);
			// int head = (Integer) paras.get(MainServiceKey.HEAD);// 该处已经废除了!

			String userName = (String) paras.get(MainServiceKey.USERNAME);
			String headName = (String) paras.get(MainServiceKey.HEAD_FILE_NAME);

			boolean result = true;

			try
			{

				SmackClient.getInstance().registUser(
						email.replace("@", "#") + "$" + nickName + "$"
								+ headName.split("\\.")[0], password);// 这个地方在注册的时候采用是用户的email+usernackName的方式
				ServerHttpUtil.userReg(email.replace("@", "#"), nickName,
						headName, password, userName);

			}
			catch (XMPPException e)
			{
				result = false;
				e.printStackTrace();
			}
			catch (Exception e)
			{
				result = false;
				e.printStackTrace();
			}

			messageObjectMap.put(MainServiceKey.RESULT_STRING, result);
			break;
		}
		case TaskType.ADD_FRIEND_GET_NICKNAME:
		{

			Map<String, Object> paras = T.get_task();

			String email = (String) paras.get(MainServiceKey.EMAIL);

			String str = ServerHttpUtil.getNiceName(email);
			String nickename;
			String head;
			try
			{
				JSONObject jo = new JSONObject(str);

				nickename = jo.getString("nickName");
				head = jo.getString("head");

				String userName = jo.getString("username");

				if (nickename != null && head != null
						&& head.equals("null") == false)
				{
					messageObjectMap.put(MainServiceKey.HEAD, head);
					messageObjectMap.put(MainServiceKey.NICK_NAME, nickename);
					messageObjectMap.put(MainServiceKey.ADD_FRIEND_RESP, true);

					messageObjectMap.put(MainServiceKey.USERNAME, userName);
				}
				else
				{
					messageObjectMap.put(MainServiceKey.ADD_FRIEND_RESP, false);
				}

			}
			catch (JSONException e)
			{
				e.printStackTrace();
				messageObjectMap.put(MainServiceKey.ADD_FRIEND_RESP, false);
			}

			break;
		}

		case TaskType.INVATE_FRIEND:
		{
			try
			{
				Map<String, Object> paras = T.get_task();
				List<String> inviteUser = (List<String>) paras
						.get(MainServiceKey.MULT_CHAT_USERS);
				String conferenceName = (String) paras
						.get(MainServiceKey.MULT_CHAT_ROOM_NAME);

				SmackClient.getInstance().createMultChat(conferenceName,
						inviteUser);
				messageObjectMap.put(MainServiceKey.RESULT_STRING, true);
			}
			catch (XMPPException e)
			{
				messageObjectMap.put(MainServiceKey.RESULT_STRING, false);
				e.printStackTrace();
			}
			break;
		}
		case TaskType.REG_EMAIL_VF:
		{
			Map<String, Object> paras = T.get_task();
			String email = (String) paras.get(MainServiceKey.EMAIL);
			String code = ServerHttpUtil.getVFcode(email);

			messageObjectMap.put(MainServiceKey.VF_CODE, code);
			// messageObjectMap.put(MainServiceKey.VF_CODE, code.substring(1,
			// 7));
			break;
		}

		case TaskType.FORGET_PASSWORD:
		{

			Map<String, Object> paras = T.get_task();
			String email = (String) paras.get(MainServiceKey.EMAIL);
			boolean resp = ServerHttpUtil.forgetPassowrd(email
					.replace("@", "#"));

			messageObjectMap.put(MainServiceKey.RESULT_STRING, resp);
			break;

		}

		case TaskType.BEFORE_SHARE_QQ:
		{
			Map<String, Object> paras = T.get_task();
			String content = (String) paras
					.get(MainServiceKey.BEFORE_SHARE_QQ_CONTENT);

			String returnFileName = ServerHttpUtil.upload(content);

			messageObjectMap.put(MainServiceKey.RESULT_STRING, returnFileName);

			break;
		}

		case TaskType.CHECK_SPELL:
		{

			Map<String, Object> paras = T.get_task();
			String content = (String) paras.get(MainServiceKey.CHECK_CONTENT);

			String returnJson = ServerHttpUtil.checkSpeel(content);
			messageObjectMap.put(MainServiceKey.RESULT_STRING, returnJson);
			break;
		}

		default:

			break;
		}
		message.obj = messageObjectMap;
		_handler.sendMessage(message);
	}

	// 接受广播
	class CommandReceiver extends BroadcastReceiver
	{

		@Override
		public void onReceive(Context context, Intent intent)
		{
			int cmd = intent.getIntExtra(CMD, -1);
			context.unregisterReceiver(this);
			if (cmd == MainService.CMD_STOP_SERVICE)
			{// 如果等于0
				_isRunable = false;// 停止线程
				stopSelf();// 停止服务
			}

		}
	}
}
